<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="题库分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryId">
              <ao-category-select placeholder="请选择题库分类" :disabled="!!model.id" v-model="model.categoryId" returnColumn="code"  pcode=""/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="正确答案" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="correctIpt">
              <a-select v-if="model.type=='1'" v-model="model.correctIpt" placeholder="请选择正确答案" :options="itemPrefixs" @change="refresh()" allowClear>
                <!-- <a-select-option v-for="item in itemPrefixs" :key="item.prefix" :value="item.prefix">
                  {{ item.prefix }}
                </a-select-option> -->
              </a-select>
              <a-select v-else-if="model.type=='2'" v-model="model.correctIpt" mode="multiple" placeholder="请选择正确答案" @change="refresh()" :options="itemPrefixs" allowClear>
                <!-- <a-select-option v-for="item in itemPrefixs" :key="item.prefix" :value="item.prefix">
                  {{ item.prefix }}
                </a-select-option> -->
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag type="list" v-model="model.type" dictCode="question_type" placeholder="请选择类型" @change="typeChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="是否练习题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isTest">
              <j-dict-select-tag type="radioButton" v-model="model.isTest" dictCode="yn" placeholder="请选择是否练习题" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="题目内容" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="infoText">
              <a-textarea v-model="model.infoText" rows="3" placeholder="请输入题目内容" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="解析" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="analysis">
              <a-textarea v-model="model.analysis" rows="3" placeholder="请输入解析" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="题目选项" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="aoQuestionItemTable.loading"
          :columns="aoQuestionItemTable.columns"
          :dataSource="aoQuestionItemTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @deleted="valueChange"
          @added="added"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'AoQuestionForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          isTest:"0",
          type:"1"
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           categoryId: [
              { required: true, message: '请选择题库类型!'},
              {
                validator: (rule, value, callback) => {
                  if( !value ){
                    callback("请选择题库分类!")
                  } else if( value.length < 9 ){
                    callback("请选择底级分类!")
                  } else{
                    callback()
                  }
                }
              }
           ],
           correctIpt: [
              { required: true, message: '请选择正确答案!'},
           ],
           infoText: [
              { required: true, message: '请输入题目内容!'},
           ],
           type: [
              { required: true, message: '请选择类型!'},
           ],
           isTest: [
              { required: true, message: '请选择是否练习题!'},
           ],
        },
        refKeys: ['aoQuestionItem', ],
        tableKeys:['aoQuestionItem', ],
        activeKey: 'aoQuestionItem',
        // 题目选项
        aoQuestionItemTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '选项',
              key: 'prefix',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: true,
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '选项内容',
              key: 'infoText',
              type: FormTypes.input,
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
          ]
        },
        url: {
          add: "/question/aoQuestion/add",
          edit: "/question/aoQuestion/edit",
          queryById: "/question/aoQuestion/queryById",
          aoQuestionItem: {
            list: '/question/aoQuestion/queryAoQuestionItemByMainId'
          },
        },
        prefixs: ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
        itemPrefixs: []
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      refresh(){
        this.$forceUpdate()
      },
      //题目类型变更需要重新选择正确答案
      typeChange(val){
        if( val === '2' ){
          this.model = Object.assign(this.model, {
            correct: undefined,
            correctIpt: [] 
          })
        }else{
          this.model = Object.assign(this.model, {
            correct: undefined,
            correctIpt: undefined
          })
        }
      },
      //动态赋值选项到正确答案并排序选项
      valueChange(){
        let that = this
        this.$refs.aoQuestionItem.getValues(function(index,rows){
          let ids = [];
          for( var i = 0 ; i < rows.length ; i++ ){
            ids.push(rows[i].id);
          }
          rows.sort(function(a,b){
            return that.prefixs.indexOf(a.prefix) - that.prefixs.indexOf(b.prefix)
          })
          let sortData = [];
          for(var i = 0 ; i < ids.length ; i++ ){
            sortData.push({
              rowKey: ids[i],
              values: {
                prefix: rows[i].prefix,
                infoText: rows[i].infoText
              }
            })
          }
          that.$refs.aoQuestionItem.setValues(sortData);
          let itemPrefixs = rows.map(item=>{
            return {
              label: item.prefix,
              value: item.prefix,
              key: item.prefix
            }
          })
          that.itemPrefixs = itemPrefixs;
          that.typeChange(that.model.type)
        })
      },
      //生成选项规则
      added(t){
        let that = this;
        this.$refs.aoQuestionItem.getValues(function(index,rows){
          let overLimitFlag = true
          for(var i = 0 ; i < that.prefixs.length ; i++){
            let flag = false
            for(var j = 0 ; j < rows.length ; j++ ){
              if( rows[j].prefix === that.prefixs[i] ){
                flag = true
              }
            }
            if( flag === false ){
              that.$refs.aoQuestionItem.setValues([{
                rowKey: t.row.id,
                values: {
                  prefix: that.prefixs[i]
                }
              }]);
              overLimitFlag = false
              break;
            }
          }
          //超出26个字母限制
          if( overLimitFlag ){
            that.$refs.aoQuestionItem.removeRows(t.row.id);
          }
          that.valueChange();
        },false);
      },
      addBefore(){
        this.aoQuestionItemTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let that = this
        this.$nextTick(() => {
          if( this.model.correct && this.model.type === '2' ){
            this.model.correctIpt = this.model.correct.split(",")
          }else{
            this.model.correctIpt = this.model.correct
          }
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.aoQuestionItem.list, params, this.aoQuestionItemTable,function(res){
            if( res.success && res.result ){
              that.itemPrefixs = res.result.map(item=>{
                return {
                  label: item.prefix,
                  key: item.prefix,
                  value: item.prefix
                }
              })
            }
          })
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        if( typeof main.correctIpt === 'object' ){
          main.correct = main.correctIpt.join(",")
        } else {
          main.correct = main.correctIpt
        }
        return {
          ...main, // 展开
          aoQuestionItemList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      handleCategoryChange(value,backObj){
        this.model = Object.assign(this.model, backObj);
      }

    }
  }
</script>

<style scoped>
</style>